package org.tangjl.utill.itext;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

/**
 * @author tangjialin on 2016-03-18 0018.
 */
public class PDFUtils {
	public static final PDFUtils api = new PDFUtils();
	public static final Charset defaultCharset = Charset.forName("UTF-8");
	private PDFUtils(){}

	/**
	 * 创建PDF
	 * @param htmlFile 生成PDF模版的HTML文件路径
	 * @param pdfFile  PDF保存路径
	 * @throws Exception
	 */
	public boolean createPdf(File htmlFile, File pdfFile) throws IOException {
		InputStream cssInputStream = null;
		FileOutputStream outputStream = null;
		InputStream contentInputStream = null;
		try {
			String content = FileUtils.readFileToString(htmlFile, defaultCharset.name());
			content = content.replaceAll("<%@.*?%>", "");

			//如果不存在则创建该目录
			File parentFile = pdfFile.getParentFile();
			if (!parentFile.exists() && !parentFile.isDirectory()) { parentFile.mkdirs(); }
			outputStream = new FileOutputStream(pdfFile);
			contentInputStream = new ByteArrayInputStream(content.getBytes(defaultCharset));

			// 加载多个css
			String css = FileUtils.readFileToString(new File("E:\\bootstrap.min.css"), defaultCharset.name());
			css += FileUtils.readFileToString(new File("E:\\main.css"), defaultCharset.name());
			cssInputStream = new ByteArrayInputStream(css.getBytes(defaultCharset));

			Document document = new Document();
			PdfWriter writer = PdfWriter.getInstance(document, outputStream);
			document.open();
			XMLWorkerHelper.getInstance().parseXHtml(writer, document, contentInputStream, cssInputStream, defaultCharset);
			document.close();
			writer.close();
		} catch (Exception e) {
			throw new IOException(e);
		} finally {
			IOUtils.closeQuietly(outputStream);
			IOUtils.closeQuietly(cssInputStream);
			IOUtils.closeQuietly(contentInputStream);
		}
		return true;
	}
}
